package top.lixunda.ecommerce.server.good.controller;

import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import com.xxl.job.core.util.ShardingUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import top.lixunda.center.xxljob.api.dto.CopyReturnT;
import top.lixunda.center.xxljob.api.dto.CopyXxlJobInfo;
import top.lixunda.center.xxljob.api.feign.IFeignJobInfoController;
import top.lixunda.commerce.common.core.entity.MessageObject;
import top.lixunda.ecommerce.server.business.BaseController;
import top.lixunda.ecommerce.server.business.api.entity.BusinessConstants;
import top.lixunda.ecommerce.server.business.api.entity.cache.CacheLoginUser;
import top.lixunda.ecommerce.server.good.api.controller.ITestController;
import top.lixunda.ecommerce.server.user.api.entity.dto.BusinessTaskStartDTO;
import top.lixunda.ecommerce.server.user.api.entity.vo.BusinessTaskVO;
import top.lixunda.ecommerce.server.user.api.feign.IFeignBusinessTaskController;
import top.lixunda.ecommerce.server.user.api.feign.IFeignTestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 测试使用接口
 *
 * @author lixunda
 * @version time:2020/4/21 9:06
 */
@SuppressWarnings("Duplicates")
@Slf4j
@RestController
public class TestController extends BaseController implements ITestController {

    private final HttpSession httpSession;

    private final HttpServletRequest httpServletRequest;

    private final IFeignTestController feignTestController;

    private final IFeignJobInfoController jobInfoController;

    private final IFeignBusinessTaskController businessTaskController;

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    public TestController(HttpSession httpSession,
                          HttpServletRequest httpServletRequest,
                          IFeignTestController feignTestController,
                          IFeignJobInfoController jobInfoController,
                          IFeignBusinessTaskController businessTaskController) {
        this.httpSession = httpSession;
        this.httpServletRequest = httpServletRequest;
        this.feignTestController = feignTestController;
        this.jobInfoController = jobInfoController;
        this.businessTaskController = businessTaskController;
    }

    @Override
    public MessageObject<String> initProgram() {
        httpSession.setAttribute("testtest", "232343");
        return getSuccessMessageObject("成功", (String) httpSession.getAttribute("testtest"));
    }

    /**
     * 测试待办任务
     *
     * @return String
     */
    @Override
    public MessageObject<String> testBusinessTask() {
        BusinessTaskStartDTO startDTO = new BusinessTaskStartDTO();
        startDTO.setTaskName("test");
        startDTO.setMenuCode("test");
        startDTO.setAllotType(BusinessConstants.ALLOT_TYPE_QUICK);
        startDTO.setAllotTypeParam(Collections.singletonList("10000-USER"));
        startDTO.setBusinessId(1);
        startDTO.setUrgeFlag(0);
        startDTO.setConsumeMode(BusinessConstants.TASK_CONSUME_MODE_SINGLE);
        startDTO.setPushEmailFlag(1);
        startDTO.setPushPhoneFlag(0);
        startDTO.setPushWebFlag(0);
        MessageObject<List<BusinessTaskVO>> response = businessTaskController.startTask(Collections.singletonList(startDTO));
        List<BusinessTaskVO> result = response.getObject();
        for (BusinessTaskVO vo : result) {
            log.info(vo.toString());
        }
        return getSuccessMessageObject("");
    }

    /**
     * 测试springSession同步
     *
     * @return 返回结果
     */
    @Override
    public MessageObject<Map<String, String>> testSpringSession() {
        log.info("good:  sessionId1: {}  sessionId2: {}", httpSession.getId(), getHttpSessionProxy().getId());
        Map<String, String> map = new HashMap<>(4);
        MessageObject<Map<String, String>> result = feignTestController.testSpringSession();
        map.putAll(result.getObject());
        map.put("goodSession1:", httpSession.getId());
        map.put("goodSession2", getHttpSessionProxy().getId());

        Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
        if (headerNames != null) {
            String name, value;
            while (headerNames.hasMoreElements()) {
                name = headerNames.nextElement();
                value = httpServletRequest.getHeader(name);
                log.debug("header:    name = {}  value = {}", name, value);
                map.put("goodHeader:" + name, value);
            }
        }

        return getSuccessMessageObject("成功", map);
    }

    /**
     * 测试自动登录
     *
     * @return 返回结果
     */
    @Override
    public MessageObject<Map<String, String>> testAutoLogin() {
        Map<String, String> map = this.testSpringSession().getObject();

        CacheLoginUser cacheLoginUser = currentLoginUserCache();
        log.info("goodAutoLoginResult:", cacheLoginUser);
        map.put("goodAutoLoginResult:", cacheLoginUser == null ? "null" : cacheLoginUser.toString());

        return getSuccessMessageObject("成功", map);
    }

    /**
     * 添加工作任务
     *
     * @param jobInfo 工作任务信息
     * @return 返回结果
     */
    @Override
    public CopyReturnT<String> add(CopyXxlJobInfo jobInfo) {
        return jobInfoController.add(jobInfo);
    }

    /**
     * 更新工作任务
     *
     * @param jobInfo 工作任务信息
     * @return 返回结果
     */
    @Override
    public CopyReturnT<String> update(CopyXxlJobInfo jobInfo) {
        return jobInfoController.update(jobInfo);
    }

    /**
     * 移除工作任务
     *
     * @param id 工作任务编号
     * @return 返回结果
     */
    @Override
    public CopyReturnT<String> remove(int id) {
        return jobInfoController.remove(id);
    }

    /**
     * 开启工作任务
     *
     * @param id 工作任务编号
     * @return 返回结果
     */
    @Override
    public CopyReturnT<String> start(int id) {
        return jobInfoController.start(id);
    }

    /**
     * 停止工作任务
     *
     * @param id 工作任务编号
     * @return 返回结果
     */
    @Override
    public CopyReturnT<String> stop(int id) {
        return jobInfoController.stop(id);
    }

    /**
     * 1、简单任务示例（Bean模式）
     */
    @XxlJob("demoJobHandler")
    public ReturnT<String> demoJobHandler(String param) throws Exception {
        XxlJobLogger.log("XXL-JOB, Hello World.");
        log.info("XXL-JOB, Hello World.");

        for (int i = 0; i < 5; i++) {
            XxlJobLogger.log("beat at:" + i);
            log.info("beat at:" + i);
            TimeUnit.SECONDS.sleep(2);
        }
        return ReturnT.SUCCESS;
    }


    /**
     * 2、分片广播任务
     */
    @XxlJob("shardingJobHandler")
    public ReturnT<String> shardingJobHandler(String param) throws Exception {

        // 分片参数
        ShardingUtil.ShardingVO shardingVO = ShardingUtil.getShardingVo();
        XxlJobLogger.log("分片参数：当前分片序号 = {}, 总分片数 = {}", shardingVO.getIndex(), shardingVO.getTotal());
        log.info("分片参数：当前分片序号 = {}, 总分片数 = {}", shardingVO.getIndex(), shardingVO.getTotal());

        // 业务逻辑
        for (int i = 0; i < shardingVO.getTotal(); i++) {
            if (i == shardingVO.getIndex()) {
                log.info("第 {} 片, 命中分片开始处理", i);
                XxlJobLogger.log("第 {} 片, 命中分片开始处理", i);
            } else {
                log.info("第 {} 片, 命中分片开始处理", i);
                XxlJobLogger.log("第 {} 片, 命中分片开始处理", i);
            }
        }

        return ReturnT.SUCCESS;
    }


    /**
     * 3、命令行任务
     */
    @XxlJob("commandJobHandler")
    public ReturnT<String> commandJobHandler(String param) throws Exception {
        String command = param;
        int exitValue = -1;

        BufferedReader bufferedReader = null;
        try {
            // command process
            Process process = Runtime.getRuntime().exec(command);
            BufferedInputStream bufferedInputStream = new BufferedInputStream(process.getInputStream());
            bufferedReader = new BufferedReader(new InputStreamReader(bufferedInputStream));

            // command log
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                XxlJobLogger.log(line);
                log.info(line);
            }

            // command exit
            process.waitFor();
            exitValue = process.exitValue();
        } catch (Exception e) {
            XxlJobLogger.log(e);
            log.info(e.getMessage());
        } finally {
            if (bufferedReader != null) {
                bufferedReader.close();
            }
        }

        if (exitValue == 0) {
            return IJobHandler.SUCCESS;
        } else {
            return new ReturnT<String>(IJobHandler.FAIL.getCode(), "command exit value(" + exitValue + ") is failed");
        }
    }


    /**
     * 4、跨平台Http任务
     * 参数示例：
     * "url: http://www.baidu.com\n" +
     * "method: get\n" +
     * "data: content\n";
     */
    @XxlJob("httpJobHandler")
    public ReturnT<String> httpJobHandler(String param) throws Exception {

        // param parse
        if (param == null || param.trim().length() == 0) {
            XxlJobLogger.log("param[" + param + "] invalid.");
            log.info("param[" + param + "] invalid.");
            return ReturnT.FAIL;
        }
        String[] httpParams = param.split("\n");
        String url = null;
        String method = null;
        String data = null;
        for (String httpParam : httpParams) {
            if (httpParam.startsWith("url:")) {
                url = httpParam.substring(httpParam.indexOf("url:") + 4).trim();
            }
            if (httpParam.startsWith("method:")) {
                method = httpParam.substring(httpParam.indexOf("method:") + 7).trim().toUpperCase();
            }
            if (httpParam.startsWith("data:")) {
                data = httpParam.substring(httpParam.indexOf("data:") + 5).trim();
            }
        }

        // param valid
        if (url == null || url.trim().length() == 0) {
            XxlJobLogger.log("url[" + url + "] invalid.");
            log.info("url[" + url + "] invalid.");
            return ReturnT.FAIL;
        }
        if (method == null || !Arrays.asList("GET", "POST").contains(method)) {
            XxlJobLogger.log("method[" + method + "] invalid.");
            log.info("method[" + method + "] invalid.");
            return ReturnT.FAIL;
        }

        // request
        HttpURLConnection connection = null;
        BufferedReader bufferedReader = null;
        try {
            // connection
            URL realUrl = new URL(url);
            connection = (HttpURLConnection) realUrl.openConnection();

            // connection setting
            connection.setRequestMethod(method);
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setReadTimeout(5 * 1000);
            connection.setConnectTimeout(3 * 1000);
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            connection.setRequestProperty("Accept-Charset", "application/json;charset=UTF-8");

            // do connection
            connection.connect();

            // data
            if (data != null && data.trim().length() > 0) {
                DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
                dataOutputStream.write(data.getBytes("UTF-8"));
                dataOutputStream.flush();
                dataOutputStream.close();
            }

            // valid StatusCode
            int statusCode = connection.getResponseCode();
            if (statusCode != 200) {
                throw new RuntimeException("Http Request StatusCode(" + statusCode + ") Invalid.");
            }

            // result
            bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            StringBuilder result = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                result.append(line);
            }
            String responseMsg = result.toString();

            XxlJobLogger.log(responseMsg);
            log.info(responseMsg);
            return ReturnT.SUCCESS;
        } catch (Exception e) {
            XxlJobLogger.log(e);
            log.info(e.getMessage());
            return ReturnT.FAIL;
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (connection != null) {
                    connection.disconnect();
                }
            } catch (Exception e2) {
                XxlJobLogger.log(e2);
                log.info(e2.getMessage());
            }
        }

    }

    /**
     * 5、生命周期任务示例：任务初始化与销毁时，支持自定义相关逻辑；
     */
    @XxlJob(value = "demoJobHandler2", init = "init", destroy = "destroy")
    public ReturnT<String> demoJobHandler2(String param) throws Exception {
        XxlJobLogger.log("XXL-JOB, Hello World.");
        return ReturnT.SUCCESS;
    }

    public void init() {
        log.info("init");
    }

    public void destroy() {
        log.info("destory");
    }
}
